const { createConnection } = require('../config/dbConfig');
const gameDBConfig = require('../config/gameDBConfig');

const getGames = async () => {
    const connection = await createConnection(gameDBConfig);
    const [rows] = await connection.execute('SELECT * FROM games');
    connection.end();
    return rows;
};

const getGameById = async (id) => {
    const connection = await createConnection(gameDBConfig);
    const [rows] = await connection.execute('SELECT * FROM games WHERE id = ?', [id]);
    connection.end();
    return rows[0];
};

const addGame = async (game) => {
    const connection = await createConnection(gameDBConfig);
    const [result] = await connection.execute('INSERT INTO games (title, description, category, release_date, image) VALUES (?,?,?,?,?)', [
        game.title,
        game.description,
        game.category,
        game.release_date,
        game.image
    ]);
    connection.end();
    return result.insertId;
};

const updateGame = async (id, game) => {
    const connection = await createConnection(gameDBConfig);
    await connection.execute('UPDATE games SET title = ?, description = ?, category = ?, release_date = ?, image = ? WHERE id = ?', [
        game.title,
        game.description,
        game.category,
        game.release_date,
        game.image,
        id
    ]);
    connection.end();
};

const deleteGame = async (id) => {
    const connection = await createConnection(gameDBConfig);
    await connection.execute('DELETE FROM games WHERE id = ?', [id]);
    connection.end();
};

module.exports = {
    getGames,
    getGameById,
    addGame,
    updateGame,
    deleteGame
};